package com.xiangyueEducation.uploaderCloud.testa;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
@Slf4j
public class TestA {

    @Autowired
    RabbitTemplate rabbitTemplate;



    @RabbitListener(queues = "test.queue")
    public void processMsg(String data, Message msg, Channel channel) throws IOException {
        //deliveryTag: 消息投递标签(是消息的唯一标识)
        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
        try{
            log.info("消息成功接收: {}",data);
            //multiple: 是否批量处理，true:批量处理，false:单个处理
            //批量处理处理的范围是[0,deliveryTag]
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            log.error("消息处理失败: {}",data);

            //如果之前入队过一次就丢弃
            if (msg.getMessageProperties().getRedelivered()){
                //basicNack(long deliveryTag, boolean multiple, boolean requeue)
                //- multiple: 是否批量处理，true:批量处理，false:单个处理
                //- requeue: 是否重新入队，true:重新入队，false:丢弃
                channel.basicNack(deliveryTag,false,false);
            }else {
//                channel.basicNack(deliveryTag,false,true);
                channel.basicReject(deliveryTag,false);
                //basicNack和basicReject的唯一区别就是basicNack可以批量处理.其他的效果都一样
            }
        }
        MessagePostProcessor messagePostProcessor = msg1->{
            msg1.getMessageProperties().setExpiration("5000");
            return msg1;
        };
        rabbitTemplate.convertAndSend("test.exchange","test.routingKey",data,messagePostProcessor);



    }


}
